<?php

namespace app\shop\controller;

use think\Controller;

class Team extends Controller
{
    public function __construct()
    {
        parent::__construct();

        $this->ProductModel = model('Product.Product');
        $this->BusinessModel = model('Business.Business');
        $this->AddressModel = model('Business.Address');
        $this->TeamOrderModel = model('Team.Order');
        $this->TeamBusinessModel = model('Team.Business');
        $this->RecordModel = model('Business.Record');

        // 规格属性
        $this->RelationModel = model('Product.Attribute.Relation');
        $this->AttributeModel = model('Product.Attribute.Attribute');
    }

    //查询拼团列表
    public function index()
    {
        $page = $this->request->param('page', 1, 'trim');
        $proid = $this->request->param('proid', 0, 'trim');

        //默认去查询正在拼团的记录 team_order.status
        $where = ['order.status' => '1'];

        if($proid)
        {
            $where['proid'] = $proid;
        }

        $limit = 8;
        //偏移量
        $offset = ($page-1)*$limit;

        $list = $this->TeamOrderModel
            ->with(['product'])
            ->where($where)
            ->order('createtime desc')
            ->limit($offset, $limit)
            ->select();

        if($list)
        {
            $this->success('返回列表', null, $list);
            exit;
        }else
        {
            $this->error('暂无更多数据');
            exit;
        }
    }

    //查询拼团详情 
    public function info()
    {
        if($this->request->isAjax())
        {
            $teamid = $this->request->param('teamid',0,'trim');

            //将关联的商品和发起人查找出来
            $team = $this->TeamOrderModel->with(['product','business'])->find($teamid);

            if(!$team)
            {
                $this->error('拼团记录不存在');
                exit;
            }

            //找出拼团的成员
            $list = $this->TeamBusinessModel
                         ->with(['businfo'])
                         ->where(['teamid'=> $teamid])
                         ->select();

            //组装的数据
            $data = [
                'team' => $team,
                'list' => $list, 
            ];

            $this->success('返回拼团成员名单',null,$data);
        }
    }

    //参与拼团
    public function add()
    {
        if($this->request->isAjax())
        {
            $busid = $this->request->param('busid', 0, 'trim');
            $proid = $this->request->param('proid', 0, 'trim');
            $teamid = $this->request->param('teamid', 0, 'trim');
            $relationids = $this->request->param('relationids', "0", 'trim');
            $addrid = $this->request->param('addrid', 0, 'trim');
            $remark = $this->request->param('remark', 0, 'trim');
            $pay = $this->request->param('pay', 'money', 'trim');

            //根据手机号码查询用户是否存在
            $business = $this->BusinessModel->find($busid);

            if (!$business) 
            {
                $this->error('该用户不存在');
                exit;
            }

            $product = $this->ProductModel->find($proid);

            if (!$product) 
            {
                $this->error('商品不存在');
                exit;
            }

            $address = $this->AddressModel->find($addrid);
        
            if (!$address) 
            {
                $this->error('收件地址不存在');
                exit;
            }

            //找出拼团的订单
            $team = $this->TeamOrderModel->find($teamid);

            if(!$team)
            {
                $this->error('未参加任何拼团订单');
                exit;
            }

            //判断活动是否还在进行中
            if($team['status'] == '0')
            {
                $this->error('拼团活动已结束！');
                exit;
            }

            if($team['proid'] != $proid)
            {
                $this->error('拼团商品不相同');
                exit;
            }

            //查询这个人是否有重复参与拼团
            $record = $this->TeamBusinessModel->where(['teamid' => $teamid, 'busid' => $busid])->find();

            if($record)
            {
                $this->error('不能重复参与拼团');
                exit;
            }

            $TeamTotal = $this->TeamBusinessModel->where(['teamid' => $teamid])->count();

            if($TeamTotal >= $team['total'])
            {
                $this->error('拼团人数已满！');
                exit;
            }

            //拼团价格计算
            $total = $product['team'];
            $attrs = [];

            $relation = $this->RelationModel->with(['attribute'])->select($relationids);

            //根据规格计算商品单价，在计算总价
            if(!empty($relation)) //无规格
            {
                foreach($relation as $item)
                {
                    //添加规格的价格
                    $total = bcadd($total, $item['price']);
                    $attrs[] = [
                        'title' => isset($item['attribute']['name']) ? $item['attribute']['name'] : '',
                        'value' => $item['value'],
                        'price' => $item['price']
                    ];
                }
            }

            $UpdateMoney = bcsub($business['money'], $total);

            //判断用户余额是否够减
            if($UpdateMoney < 0)
            {
                $this->error('余额不足请先充值');
                exit;
            }

            //team_order_business 参与表增加记录
            // business 更新余额
            // 消费记录表 插入

            $this->TeamBusinessModel->startTrans();
            $this->BusinessModel->startTrans();
            $this->RecordModel->startTrans();


            //参与拼团表
            $TeamData = [
                'teamid' => $teamid,
                'busid' => $busid,
                'addrid' => $addrid,
                'proid' => $proid,
                'total' => $total,
                'attrs' => empty($attrs) ? NULL : json_encode($attrs),
                'remark' => $remark,
            ];

            //插入
            $TeamStatus = $this->TeamBusinessModel->save($TeamData);

            if($TeamStatus === FALSE)
            {
                $this->error($this->TeamBusinessModel->getError());
                exit;
            }


            // 用户余额更新
            $BusinessStatus = $this->BusinessModel->where('id', $busid)->update(['money' => $UpdateMoney]);

            if ($BusinessStatus === FALSE) 
            {
                $this->TeamBusinessModel->rollback();
                $this->error($this->BusinessModel->getError());
                exit;
            }

            //消费记录表
            $RecordData = [
                'total' => "-$total",
                'busid' => $busid,
                'content' => "参与拼团---消费的金额：$total 元",
            ];

            //插入语句
            $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);

            if ($RecordStatus === FALSE) 
            {
                $this->BusinessModel->rollback();
                $this->TeamBusinessModel->rollback();
                $this->error($this->RecordModel->getError());
                exit;
            }

            if($TeamStatus === FALSE || $BusinessStatus === FALSE || $RecordStatus === FALSE)
            {
                $this->RecordModel->rollback();
                $this->BusinessModel->rollback();
                $this->TeamBusinessModel->rollback();
                $this->error('拼团失败');
                exit;
            }else
            {
                $this->TeamBusinessModel->commit();
                $this->BusinessModel->commit();
                $this->RecordModel->commit();
                $this->success('拼团成功');
                exit;
            }
        }
    }
}